require 'base64'

default_platform(:ios)

platform :ios do
  
  before_all do
    xcode_select "/Applications/Xcode.app" # Set the default path to Xcode
  end

  # For TestFlight (staging)
  lane :beta do
    setup_keychain()
    
    match(
      type: 'appstore',
      readonly: true,
      git_url: "https://github.com/meditohq/fastlane-certificates.git",
      git_basic_authorization: Base64.strict_encode64("x-access-token:#{ENV['MATCH_GIT_TOKEN']}")
    )

    build_app(
      workspace: "Runner.xcworkspace",
      configuration: "Release",
      scheme: "Runner",
      export_method: "app-store",
      export_options: {
        provisioningProfiles: {
          ENV["DEVELOPER_APP_IDENTIFIER"] => ENV["PROVISIONING_PROFILE_SPECIFIER"]
        }
      }
    )

    upload_to_testflight(skip_submission: true)
    cleanup_keychain()
  end
  
  # For App Store (production)
  lane :release do
    setup_keychain()
    
    match(
      type: 'appstore',
      readonly: true,
      git_url: "https://github.com/meditohq/fastlane-certificates.git",
      git_basic_authorization: Base64.strict_encode64("x-access-token:#{ENV['MATCH_GIT_TOKEN']}")
    )

    build_app(
      workspace: "Runner.xcworkspace",
      configuration: "Release",
      scheme: "Runner",
      export_method: "app-store",
      export_options: {
        provisioningProfiles: {
          ENV["DEVELOPER_APP_IDENTIFIER"] => ENV["PROVISIONING_PROFILE_SPECIFIER"]
        }
      }
    )

    upload_to_app_store()
    cleanup_keychain()
  end
end

# Helper methods to manage keychain
def setup_keychain
  create_keychain(
    name: ENV["TEMP_KEYCHAIN_USER"],
    password: ENV["TEMP_KEYCHAIN_PASSWORD"],
    default_keychain: true,
    unlock: true,
    timeout: 3600,
    lock_when_sleeps: true
  )
end

def cleanup_keychain
  delete_keychain(name: ENV["TEMP_KEYCHAIN_USER"])
end
